#ifndef DATABASE_TEST_H
#define DATABASE_TEST_H

#include "include/gtest.h"
#include "../Tool/include/Variant.h"
#include "../Tool/include/MiniDatabase.h"
#include "../Tool/include/ILogger.h"
using namespace Tool;

TEST(Database, BasicOperations)
{
    // 创建数据库实例
    MiniDatabase db("test_database.db");
    LOG_INFO("创建数据库实例: test_database.db");

    // 定义用户表结构
    std::vector<FieldDefinition> userFields = {
        FieldDefinition("id", FieldType::Int, true, false),        // 主键，非空
        FieldDefinition("name", FieldType::String, false, false),  // 非空
        FieldDefinition("age", FieldType::Int, false, true),
        FieldDefinition("email", FieldType::String, false, true),
        FieldDefinition("is_active", FieldType::Bool, false, true, true)  // 默认值true
    };

    // 创建表
    bool createSuccess = db.CreateTable("users", userFields);
    LOG_INFO("创建users表: %s", createSuccess ? "成功" : "失败");

    // 获取表对象
    Table* usersTable = db.GetTable("users");
    if (usersTable)
    {
        LOG_INFO("获取users表成功");
    }
    else
    {
        LOG_ERROR("获取users表失败");
        return;
    }

    // 插入测试数据
    VariantHash user1;
    user1["id"] = 1;
    user1["name"] = "张三";
    user1["age"] = 25;
    user1["email"] = "zhangsan@example.com";
    
    VariantHash user2;
    user2["id"] = 2;
    user2["name"] = "李四";
    user2["age"] = 30;
    user2["email"] = "lisi@example.com";
    user2["is_active"] = false;

    bool insert1 = usersTable->Insert(user1);
    bool insert2 = usersTable->Insert(user2);
    LOG_INFO("插入记录1: %s, 插入记录2: %s", insert1 ? "成功" : "失败", insert2 ? "成功" : "失败");
    LOG_INFO("当前记录总数: %zu", usersTable->GetRecordCount());

    // 查询所有记录
    auto allUsers = usersTable->Query();
    LOG_INFO("\n查询所有记录 (共%d条):", (int)allUsers.size());
    for (auto& user : allUsers)
    {
        LOG_INFO("ID: %d, 姓名: %s, 年龄: %d, 状态: %s", user["id"].ToInt(), user["name"].ToString().c_str(), user["age"].ToInt(), user["is_active"].ToBool() ? "活跃" : "禁用");
    }

    // 条件查询
    auto condition = ConditionBuilder::GreaterThan("age", 28);
    auto adultUsers = usersTable->Query({"id", "name", "age"}, condition);
    LOG_INFO("\n查询年龄大于28的记录 (共%d条):", (int)adultUsers.size());
    for (auto& user : adultUsers)
    {
        LOG_INFO("ID: %d, 姓名: %s, 年龄: %d",
                 user["id"].ToInt(),
                 user["name"].ToString().c_str(),
                 user["age"].ToInt());
    }

    // 更新记录
    VariantHash updates;
    updates["age"] = 26;
    size_t updated = usersTable->Update(updates, ConditionBuilder::Equals("id", 1));
    LOG_INFO("\n更新ID=1的记录: %zu条记录被更新", updated);

    // 验证更新结果
    auto updatedUser = usersTable->Query({"id", "name", "age"}, ConditionBuilder::Equals("id", 1));
    if (!updatedUser.empty())
    {
        LOG_INFO("更新后的数据: ID: %d, 年龄: %d",
                 updatedUser[0]["id"].ToInt(),
                 updatedUser[0]["age"].ToInt());
    }

    // 删除记录
    size_t deleted = usersTable->Remove(ConditionBuilder::Equals("id", 2));
    LOG_INFO("\n删除ID=2的记录: %zu条记录被删除", deleted);
    LOG_INFO("删除后记录总数: %zu", usersTable->GetRecordCount());

    // 保存数据库
    bool saveSuccess = db.Save();
    LOG_INFO("\n保存数据库: %s", saveSuccess ? "成功" : "失败");
}

TEST(Database, TransactionTest)
{
    MiniDatabase db("test_database.db");
    Table* usersTable = db.GetTable("users");
    if (!usersTable)
    {
        LOG_ERROR("获取users表失败，无法进行事务测试");
        return;
    }

    // 测试事务
    LOG_INFO("\n=== 事务测试开始 ===");
    bool beginTx = db.BeginTransaction();
    LOG_INFO("开始事务: %s", beginTx ? "成功" : "失败");

    // 插入测试数据
    VariantHash user3;
    user3["id"] = 3;
    user3["name"] = "王五";
    user3["age"] = 35;
    bool insert3 = usersTable->Insert(user3);
    LOG_INFO("在事务中插入记录3: %s", insert3 ? "成功" : "失败");
    LOG_INFO("事务中记录总数: %zu", usersTable->GetRecordCount());

    // 回滚事务
    bool rollbackTx = db.RollbackTransaction();
    LOG_INFO("回滚事务: %s", rollbackTx ? "成功" : "失败");
    LOG_INFO("回滚后记录总数: %zu", usersTable->GetRecordCount());

    // 再次测试提交事务
    beginTx = db.BeginTransaction();
    LOG_INFO("再次开始事务: %s", beginTx ? "成功" : "失败");
    
    insert3 = usersTable->Insert(user3);
    LOG_INFO("再次插入记录3: %s", insert3 ? "成功" : "失败");
    
    bool commitTx = db.CommitTransaction();
    LOG_INFO("提交事务: %s", commitTx ? "成功" : "失败");
    LOG_INFO("提交后记录总数: %zu", usersTable->GetRecordCount());
}

TEST(Database, TransactionExecute)
{
    MiniDatabase db("test_database.db");
    Table* usersTable = db.GetTable("users");
    if (!usersTable)
    {
        LOG_ERROR("获取users表失败，无法进行事务测试");
        return;
    }

    // 插入数据
    ExecuteResult result = db.Execute("INSERT INTO users SET id=1, name='张三', age=25");
    LOG_INFO("插入了 %zu 条记录", result.m_affectedRows);

    result = db.Execute("INSERT INTO users SET id=4, name='李四', age=21");
    LOG_INFO("插入了 %zu 条记录", result.m_affectedRows);

    // 查询数据
    result = db.Execute("SELECT name, age FROM users WHERE age > 18");
    LOG_INFO("查询到 %zu 条记录", result.m_result.size());
    for (const auto& row : result.m_result)
    {
        LOG_INFO("姓名: %s, 年龄: %d", row.at("name").ToString().c_str(), row.at("age").ToInt());
    }
    LOG_INFO("Execute == end");
}
#endif // DATABASE_TEST_H
    